var Utils = {};

var upload;
var element;
layui.use(['upload', 'element'], function () {
    upload = layui.upload;
    element = layui.element;
});

// tinyMCE富文本框
Utils.initTinymce = function (conf) {
    if (!conf || !conf.selector) {
        console.error("富文本没有指定ID！");
        return;
    }
    conf.mode = "textareas";
    tinymce.remove(conf.selector);
    if (!conf.plugins) {
        conf.plugins = [
            "advlist autolink lists link image charmap print preview anchor",
            "searchreplace visualblocks code fullscreen",
            "insertdatetime media table paste imagetools wordcount"
        ];
    }
    if (!conf.language) {
        conf.language = "zh_CN";
    }
    if (!conf.height) {
        conf.height = 300;
    }
    if (!conf.toolbar) {
        conf.toolbar = "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | fontsizeselect | fontselect";
    }
    if (!conf.fontsize_formats) {
        conf.fontsize_formats = "8pt 9pt 10pt 11pt 12pt 14pt 18pt 24pt 36pt";
    }
    if (!conf.font_formats) {
        conf.font_formats = "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Arial='Arial';" +
            "Andale Mono=andale mono,monospace;Arial=arial,helvetica,sans-serif;Arial Black=arial black,sans-serif;" +
            "Book Antiqua=book antiqua,palatino,serif;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier,monospace;" +
            "Georgia=georgia,palatino,serif;Helvetica=helvetica,arial,sans-serif;Impact=impact,sans-serif;Symbol=symbol;" +
            "Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco,monospace;Times New Roman=times new roman,times,serif;" +
            "Trebuchet MS=trebuchet ms,geneva,sans-serif;Verdana=verdana,geneva,sans-serif;Webdings=webdings;Wingdings=wingdings,zapf dingbats";
    }
    if (!conf.images_upload_handler) {
        conf.images_upload_handler = function (blobInfo, success, failure) {
            var xhr, formData;
            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', '<%=basePath%>/common/upload');
            xhr.onload = function () {
                var json;
                if (xhr.status !== 200) {
                    failure('HTTP Error: ' + xhr.status);
                    return;
                }
                json = JSON.parse(xhr.responseText);
                success(json.entity.url);
            };
            formData = new FormData();
            formData.append('file', blobInfo.blob());
            xhr.send(formData);
        };
    }
    tinymce.init(conf);
};

/**
 * 图片上传事件注册：带index的动态注册
 * param id
 * param index
 * param done
 * param accept：images（图片）、file（所有文件）、video（视频）、audio（音频）
 */
Utils.addUploadEvent = function (id, index, done, accept) {
    this.addUploadEvents("#" + id + index, index, done, accept);
};

/**
 * 图片上传事件注册：固定ID，不需要动态生成时使用
 * param id
 * param done
 * param accept：images（图片）、file（所有文件）、video（视频）、audio（音频）
 */
Utils.addUploadEventById = function (id, done, accept) {
    this.addUploadEvents("#" + id, id, done, accept);
};

/**
 * 文件上传空间全局实例容器，存放的是以id为标识的图片上传实例
 */
var uploadInst = [];

/**
 * 图片上传事件注册
 * param idSelector
 * param index
 * param done
 * param accept：images（图片）、file（所有文件）、video（视频）、audio（音频）
 */
Utils.addUploadEvents = function (idSelector, index, done, accept) {
    var acceptMime;
    switch (accept) {
        case 'images':
            acceptMime = 'image/*';
            break;
        case 'file':
            acceptMime = '*';
            break;
        case 'video':
            acceptMime = 'video/*';
            break;
        case 'audio':
            acceptMime = 'audio/*';
            break;
        default:
            acceptMime = null;
            accept = null;
            break;
    }
    var renders = {
        elem: idSelector //绑定元素
        , accept: 'file'
        , url: '<%=basePath%>/common/upload' //上传接口
        , before: function (obj) {
            layer.load(); //上传loading
        }
        , done: function (res) {
            done(res);
            layer.closeAll('loading');
        }
        , error: function (res) {
            //请求异常回调
            layer.error("上传失败")
        }
    };
    if (accept) {
        renders.acceptMime = acceptMime;
        renders.accept = accept;
    }
    uploadInst[index] = null;
    $(idSelector).click(function () {
        if (!uploadInst[index]) {
            //初始化上传基地图片
            uploadInst[index] = upload.render(renders);
            $(idSelector).click();
        }
        uploadInst[index].upload();
    });
};

// 根据生日计算年龄：格式yyyy-MM-dd
Utils.getAge = function (brith) {
    if (!brith) {
        return '';
    }
    var strBirthdayArr = brith.split("-");
    var d = new Date();
    var yearDiff = d.getFullYear() - strBirthdayArr[0];
    var monthDiff = d.getMonth() + 1 - strBirthdayArr[1];
    var dayDiff = d.getDate() - strBirthdayArr[2];
    var age = monthDiff < 0 || (monthDiff === 0 && dayDiff < 0) ? yearDiff - 1 : yearDiff; //判断有没有到生日,没到就减1
    return age < 0 ? 0 : age;
};